﻿using System;
using System.IO;
using Auth.Application;
using Microsoft.AspNetCore.Mvc;
using Auth.Application.Dtos;
using Auth.SqlSugar.IocManager;
using Microsoft.AspNetCore.Http;
using Auth.Utility;
using Auth.Web.Models;
using AutoMapper;
using Microsoft.Extensions.Configuration;

namespace Auth.Web.Controllers
{
    public class LoginController : Controller
    {
        private readonly IUserAppService _userAppService;
        private readonly IHttpContextAccessor _httpContext;

        public LoginController(IUserAppService userAppService,IHttpContextAccessor httpContext)
        {
            _userAppService = userAppService;
            _httpContext = httpContext;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public JsonResult Test()
        {
           var res= IocManager.Resolve<IRoleAppService>().GetAll();
           var code = _httpContext.HttpContext.Session.GetString("LoginValidateCode");
           return Json(code);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                //检查用户信息
                var user = _userAppService.CheckUser(model.UserName, model.Password);
                if (user != null)
                {
                    //记录Session
                    HttpContext.Session.SetString("CurrentUserId", user.Id);
                    HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(user));
                    user.LastLoginTime = DateTime.Now;
                    user.LoginTimes++;
                    UserDto userDto = Mapper.Map<UserDto>(user);
                    _userAppService.InsertOrUpdate(userDto);
                    //跳转到系统首页
                    return Json(new ReturnModel { Msg = "登录成功"});
                }

                return Json(new ReturnModel {Success = false, Msg = "用户名或密码错误"});
            }

            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    return Json(new ReturnModel {Success = false,Msg = item.Errors[0].ErrorMessage});

                }
            }

            return Json(new ReturnModel {Success = false, Msg = "登录失败"});
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns>image</returns>
        [HttpGet]
        public IActionResult ValidateCode()
        {
            //var db = DbInstance.GetInstance();
            //db.DbFirst.CreateClassFile("D:\\dotnetCoreWorkSpace\\netCoreAuthority\\Auth.Domain\\TableEntity");
            VierificationCode vierificationCode=new VierificationCode();
            MemoryStream ms = vierificationCode.Create(out var code);
            HttpContext.Session.SetString("LoginValidateCode", code);
            Response.Body.Dispose();
            return File(ms.ToArray(), @"image/png");
        }
    }
}